//
//  XYTUserInfoManager.m
//  XYTPayOrderSystem
//
//  Created by wupeng on 2017/8/23.
//  Copyright © 2017年 wupeng. All rights reserved.
//

#import "XYTUserInfoManager.h"

@implementation XYTUserInfoManager

+ (XYTUserInfoManager *)sharedManager
{
    static XYTUserInfoManager *sharedInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (id)init
{
    self = [super init];
    
    if (self) {
        [self readUserInfo];
    }
    return self;
}

#pragma mark - NSCoding
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    
    if (self) {
        [self decodeAllVariables:aDecoder];
    }
    return self;
}
- (void)decodeAllVariables:(NSCoder *)aDecoder{
    self.phone = [aDecoder decodeObjectForKey:@"phone"];
    self.token = [aDecoder decodeObjectForKey:@"token"];
    self.roleType = [[aDecoder decodeObjectForKey:@"roleType"] integerValue];
    self.userId = [[aDecoder decodeObjectForKey:@"userId"] integerValue];
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.phone forKey:@"phone"];
    [aCoder encodeObject:self.token forKey:@"token"];
    [aCoder encodeObject:@(self.roleType) forKey:@"roleType"];
    [aCoder encodeObject:@(self.userId) forKey:@"userId"];
}

#pragma mark - private Methods
- (void)saveUserInfo
{
    NSString *path = [self getUserInfoPath];
    
    [NSKeyedArchiver archiveRootObject:self toFile:path];
}

-(void)clearUserInfo{
    //清空用户基本信息
    NSDictionary *members = [self getClassAllMembersToDictionary];
    
    for (NSString *key in members) {
        id value = [members objectForKey:key];
        NSString *type = NSStringFromClass([value class]);
        if ([type rangeOfString:@"Number"].location != NSNotFound ||
            [type rangeOfString:@"Boolean"].location != NSNotFound) {
            
            [self setValue:@(0) forKey:key];
        }else{
            
            [self setValue:nil forKey:key];
        }
    }
    
    [self saveUserInfo];
}

- (void)readUserInfo
{
    NSString *path = [self getUserInfoPath];
    
    XYTUserInfoManager *userInfo = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    
    NSDictionary *members = [userInfo getClassAllMembersToDictionary];
    
    for (NSString *key in members) {
        id value = [members objectForKey:key];
        [self setValue:value forKey:key];
    }
}

-(void)loginOutAll
{
    
    [self clearUserInfo];
}

/**
 * 获取文件路径
 */
- (NSString *)getUserInfoPath
{
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path = [docPath stringByAppendingPathComponent:@"userInfo.login"];
    
    return path;
}

#pragma mark - setter/getter


@end
